package com.dragon.logical.service.supplies.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dragon.common.model.ResultCode;
import com.dragon.common.model.exception.CustomException;
import com.dragon.repository.entity.Warehouse;
import com.dragon.repository.mapper.AdminMapper;
import com.dragon.repository.mapper.WarehouseMapper;
import com.dragon.logical.service.supplies.IWarehouseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 仓库表 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-11-13
 */
@Service
public class WarehouseServiceImpl extends ServiceImpl<WarehouseMapper, Warehouse> implements IWarehouseService {

    @Autowired
    WarehouseMapper warehouseMapper;

    @Autowired
    AdminMapper adminMapper;

    @Override
    public Page<Warehouse> warehouseList(Integer page, Integer limit, String search) {
        Page<Warehouse> warehousePage = new Page<>(page, limit);
        LambdaQueryWrapper<Warehouse> lambda = new QueryWrapper<Warehouse>().lambda();
        lambda.like(StrUtil.isNotBlank(search), Warehouse::getName, search);
        Page<Warehouse> warehouses= warehouseMapper.selectPage(warehousePage, lambda);
        warehouses.getRecords().forEach(warehouse -> {
            String username = adminMapper.selectUsernameById(warehouse.getAdminId());
            warehouse.setAdminName(username);
        });
        return warehouses;
    }

    @Override
    public void addWarehouse(Warehouse warehouse) {
        List<Warehouse> warehouses = warehouseMapper.selectList(null);
        List<String> warehouseNames = warehouses.stream().map(Warehouse::getName).collect(Collectors.toList());
        if (warehouseNames.contains(warehouse.getName())){
            throw new CustomException(ResultCode.DATA_ALREADY_EXISTS);
        }
        warehouse.setCreateTime(DateUtil.date());
        warehouseMapper.insert(warehouse);
    }

    @Override
    public void updateWarehouse(Warehouse warehouse){
        warehouseMapper.updateById(warehouse);
    }


    @Override
    public Warehouse detailById(Integer id){
        Warehouse warehouse = warehouseMapper.selectById(id);
        return warehouse;
    }

}
